package com.atguigu.spzx.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.atguigu.spzx.feign.user.UserFeignClient;
import com.atguigu.spzx.model.entity.user.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Lazy;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @author Mahone
 */
@Component
public class AuthFilter  implements GlobalFilter, Ordered {

    /**
     * GlobalFilter加载太快，导致nacos信息还没被网关获取到userFeignClient就已经完成注入，
     * 导致userFeignClient注入的nacos配置为空
     * 解决：改变GlobalFilter优先级，使得userFeignClient在nacos加载之后注入
     */
    @Lazy
    @Autowired
    private UserFeignClient userFeignClient;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 统一鉴权
        ServerHttpRequest request = exchange.getRequest();
        List<String> tokens = request.getHeaders().get("token");
        if (null != tokens && tokens.size() > 0) {
            String token = tokens.get(0);
            if (!StringUtils.isEmpty(token)) {
                System.out.println("通过token远程调用user服务校验用户");
                // 统一鉴权过滤器配接口
                UserInfo userInfo = null;
                // 非阻塞线程
                CompletableFuture<UserInfo> completableFuture = CompletableFuture.supplyAsync(() -> {
                    UserInfo currentUserInfoByToken = userFeignClient.getCurrentUserInfoByToken(token);
                    return currentUserInfoByToken;
                });
                try {
                    userInfo = completableFuture.get();
                    if (null != userInfo) {
                        System.out.println("鉴权成功");
                        // 将鉴权结果放入header
                        // 重新设置request属性，向里面传入userInfo
                        // SerializerFeature.BrowserCompatible解决中文乱码
                        request.mutate().header("userInfoJson", JSON.toJSONString(userInfo, SerializerFeature.BrowserCompatible));
                        // 重新设置exchange属性，向里面传入request
                        exchange.mutate().request(request);
                    }
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } catch (ExecutionException e) {
                    throw new RuntimeException(e);
                }
            }
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -1;
    }
}
